package com.education.welco.service.impl;


import com.education.common.config.BusinessException;
import com.education.common.utils.ApiReturnObject;
import com.education.common.utils.Convert;
import com.education.welco.feign.userFeign;
import com.education.welco.mapper.TTeacherMapper;
import com.education.welco.pojo.TTeacher;
import com.education.welco.pojo.vo.AppTeaInfoVO;
import com.education.welco.service.ITTeacherService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 教师 服务层实现
 *
 * @author d
 * @date 2020-05-08
 */
@Service
public class TTeacherServiceImpl implements ITTeacherService {

    @Autowired
    private TTeacherMapper tTeacherMapper;
    @Resource
    private userFeign userFeign;


    /**
     * 查询教师信息
     *
     * @param id 教师ID
     * @return 教师信息
     */
    @Override
    public TTeacher selectTTeacherById(Integer id) {
        return tTeacherMapper.selectTTeacherById(id);
    }

    @Override
    public TTeacher selectTTeacherById1(Integer userId) {
        return tTeacherMapper.selectTTeacherById1(userId);
    }

    /**
     * 查询教师列表
     *
     * @param deptId 教师信息
     * @return 教师集合
     */
    @Override
    public List<TTeacher> selectTTeacherListOther(Integer deptId) {
        return tTeacherMapper.selectTTeacherListOther(deptId);
    }

    /**
     * 查询教师列表
     *
     * @param tTeacher 教师信息
     * @return 教师集合
     */
    @Override
    public List<TTeacher> selectTTeacherListOther2(TTeacher tTeacher) {
        return tTeacherMapper.selectTTeacherListOther2(tTeacher);
    }

    /**
     * 查询教师列表
     *
     * @param tTeacher 教师信息
     * @return 教师集合
     */
    @Override
    public List<TTeacher> selectTTeacherList(TTeacher tTeacher) {
        return tTeacherMapper.selectTTeacherList(tTeacher);
    }

    /**
     * 新增教师
     *
     * @param tTeacher 教师信息
     * @return 结果
     */
    @Override
    public int insertTTeacher(TTeacher tTeacher) {
        return tTeacherMapper.insertTTeacher(tTeacher);
    }

    /**
     * 修改教师
     *
     * @param tTeacher 教师信息
     * @return 结果
     */
    @Override
    public int updateTTeacher(TTeacher tTeacher) {
        return tTeacherMapper.updateTTeacher(tTeacher);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateTeacherByUserId(TTeacher teacher) {
        tTeacherMapper.updateTeacherByUserId(teacher);
        return tTeacherMapper.updateTeacherForUserByUserId(teacher);
    }

    /**
     * 删除教师对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteTTeacherByIds(String ids) {
        return tTeacherMapper.deleteTTeacherByIds(Convert.toStrArray(ids));
    }

    @Override
    public AppTeaInfoVO selectTeacherInfoByUserId(Integer teaId) {
        return tTeacherMapper.selectTeacherInfoByUserId(teaId);
    }


    /**
     * 导入教师对象信息
     *
     * @param fileName 需要删除的数据ID
     * @return 结果
     */
    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public boolean threeBatchQuesionImport(String fileName, MultipartFile file, Integer schoolId) throws Exception {
        //从上传的Excel表格里面取出对象添加到数据库中   导入
        //定义一个标记，判断该文件是否为空
        boolean notNull = false;
        //matches  正则表达式    判断是不是表格的形式
        //xls 复合文档类型的结构     xlsx    xml类型结构
        if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
            //throw new Exception("上传文件格式不正确");
            throw new BusinessException(201, "上传文件格式不正确");
        }
        boolean isExcel1903 = true;
        //判断是不是表格的形式
        if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            isExcel1903 = false;
        }
        InputStream is = file.getInputStream();
        Workbook wb;
        if (isExcel1903) {
            //HSSFWorkbook操作Excel1903以前（包括1903）的版本 扩展名是.xls
            wb = new HSSFWorkbook(is);
        } else {
            //XSSFWorkbook操作Excel1907的版本，扩展名是.xlsx
            wb = new XSSFWorkbook(is);
        }
        //getSheetAt(0) 获取到excel的第一个sheet页
        Sheet sheet = wb.getSheetAt(0);
        if (sheet != null) {
            notNull = true;
        }
        TTeacher tTeacher;
        //获取总行数
        //r = 2 表示从第三行开始循环 如果你的第三行开始是数据
        for (int r = 1; r <= sheet.getLastRowNum(); r++) {
            //通过sheet表单对象得到 行对象
            Row row = sheet.getRow(r);
            if (row == null) {
                continue;//结束本次循环，开始下次循环
            }
            if (Objects.isNull(row.getCell(0))) {
                continue;
            }
            Cell cell1 = row.getCell(0);
            cell1.setCellType(CellType.STRING);
            String stringCellValue = cell1.getStringCellValue();
            if ("".equals(stringCellValue + "")) {
                continue;
            }
            //完整的循环一次
            tTeacher = new TTeacher();
            tTeacher.setSchoolId(schoolId);
            tTeacher.setCreateTime(new Date());
            //取出数据并赋值
            //老师姓名
            if (row.getCell(0) == null) {
                row.createCell(0);
            } else {
                //获取单元格
                Cell cell = row.getCell(0);
                //设置单元格类型
                cell.setCellType(CellType.STRING);
                //获取单元格数据
                String teaName = cell.getStringCellValue();
                tTeacher.setTeacherName(teaName);
            }
            //证件号码
            if (row.getCell(1) == null) {
                row.createCell(1);
            } else {
                //获取单元格
                Cell cell = row.getCell(1);
                //设置单元格类型
                cell.setCellType(CellType.STRING);
                //获取单元格数据
                String idcardno = cell.getStringCellValue();
                tTeacher.setIdcardno(idcardno);
                if (!"".equals(idcardno)) {
                    int i = 18;
                    if (i != idcardno.length()) {
                        throw new RuntimeException("导入第 " + (r + 1) + "行失败,身份证号格式有误");
                    }
                    TTeacher teacher = TTeacher.builder().idcardno(idcardno).build();
                    List<TTeacher> tTeachers = this.selectTTeacherList(teacher);
                    if (tTeachers.size() > 0) {
                        throw new RuntimeException("导入第 " + (r + 1) + "行失败,身份证号已存在 ");
                    }
                }
            }
            String phone = "";
            //账号
            if (row.getCell(2) == null) {
                row.createCell(2);
            } else {
                Cell cell = row.getCell(2);
                if (cell != null) {
                    //设置单元格类型
                    cell.setCellType(CellType.STRING);
                    phone = cell.getStringCellValue();
                }
                if (!"".equals(phone)) {
                    if (phone.length() != 11) {
                        throw new RuntimeException("导入第 " + (r + 1) + "行失败,手机号不规范");
                    }
                    TTeacher teacher = TTeacher.builder().phone(phone).build();
                    List<TTeacher> tTeachers = this.selectTTeacherList(teacher);
                    if (tTeachers.size() > 0) {
                        throw new RuntimeException("导入第 " + (r + 1) + "行失败,手机号已存在");
                        //throw  new BusinessException( CommonErrorCode.D_999917);
                    }
                    tTeacher.setPhone(phone);
                } else {
                    throw new RuntimeException("导入第 " + (r + 1) + "行失败,手机号为空");
                }
            }
            //老师简介
            if (row.getCell(3) == null) {
                row.createCell(3);
            } else {
                //获取单元格
                Cell cell = row.getCell(3);
                //设置单元格类型
                cell.setCellType(CellType.STRING);
                //获取单元格数据
                String teacherIntro = cell.getStringCellValue();
                tTeacher.setTeacherIntro(teacherIntro);
            }
            //远程调用添加用户信息   tid是教务主任id 资源共享
            ApiReturnObject apiReturnObject = userFeign.addUser(phone, "123456", schoolId, 0, tTeacher.getTeacherName());
            if ("200".equals(apiReturnObject.getCode())) {
                //添加用户成功 开始添加教师信息
                tTeacher.setUserId((int) apiReturnObject.getReturnObject());
                tTeacherMapper.insertTTeacher(tTeacher);
            } else {
                throw new RuntimeException("导入第 " + (r + 1) + "行失败," + apiReturnObject.getMessage());
            }
        }
        return notNull;
    }
}